package com.raquel.onceuponatime;


import java.io.IOException;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Connection;
import java.sql.Statement;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;


/**
 * Servlet implementation class Home
 * @author raquel_valenzuela
 */
@WebServlet("/Home")
public class Home extends HttpServlet {
	private static final long serialVersionUID = 1L;
       
    /**
     * @see HttpServlet#HttpServlet()
     */
    public Home() {
        super();
        // TODO Auto-generated constructor stub
    }

	/**
	 * @throws IOException 
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		
		//Get tales from database
		String tales = getTales();
		
		//We set tales attribute for the jsp
		request.setAttribute("tales",tales);
		
		//Redirecting to home.jsp
		redirectToHome(request, response);
	}

	private void redirectToHome(HttpServletRequest request,HttpServletResponse response) throws ServletException, IOException {
		this.getServletContext().getRequestDispatcher("/home.jsp").forward(request, response);
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		
		//Get tales from database
		String tales = getTales();
				
		//We set tales attribute for the jsp
		request.setAttribute("tales",tales);
				
		//Redirecting to home.jsp
		redirectToHome(request, response);
	}
	
	/**
	 * get all tales from database
	 * @return String
	 */
	private String getTales(){
		String allTales="";
		int id;
		String urlcon="jdbc:mysql://localhost:3306/onceupon";
		ResultSet resultSet=null;
		try{
		Class.forName("com.mysql.jdbc.Driver");
		Connection conn = (Connection)DriverManager.getConnection(urlcon,"root","");
		Statement stat= (Statement) conn.createStatement();
		resultSet= stat.executeQuery("select * from tale");
		
		while(resultSet.next()){
			id=resultSet.getInt("id");
			allTales += resultSet.getString("title");
			allTales += " | <a href='Delete?id="+id+"'>Delete</a>";
			allTales += " | <a href='Update?id="+id+"'>Update</a>";
			allTales +="<br/>";
		}
		resultSet.close();
		conn.close();
		}catch (SQLException e){
			e.printStackTrace();
		}catch(ClassNotFoundException e){
			e.printStackTrace();
		}
		
		return allTales;
	}

}
